from flask import Blueprint, render_template, request, redirect, url_for, session
from models import Usermodel

bp = Blueprint("auth", __name__, url_prefix="/auth")


@bp.route("/login", methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template("login.html")
    else:
        userid = request.form.get('userid')
        user = Usermodel.query.filter_by(id=userid).first()
        if not user:
            print("用户不存在")
            return redirect(url_for("auth.login"))
        else:
            password = request.form.get('password')
            if password == user.password:
                session['userid'] = user.id
                return redirect(url_for("index"))
            else:
                print("密码错误")
                return redirect(url_for("auth.login"))


@bp.route("/logout")
def logout():
    session.clear()
    return redirect(url_for("auth.login"))
